<?php
App::uses('AppComponent', 'Controller/Component');
App::uses('AppConst', 'Lib');

/**
 * User Model
 *
 * @property 1 $1
 */
class User extends AppModel {
	public $name = 'User';
	/**
	 * Use database config
	 *
	 * @var string
	 */
	public $useTable = 'users';
	/**
	 * Display field
	 *
	 * @var string
	 */
	public $displayField = 'id';
	public $checkUpdate = false;
	/**
	 * (non-PHPdoc)
	 * @see lib/Cake/Model/Model::beforeSave()
	 */
	public function beforeSave() {
	    if($this->checkUpdate === false){
            if($this->data['User']['password'] != '')
                $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
        }
        return true;
    }
 
    /**
	 * Get all user by condition
	 */
	public function getOneUserByCondition($field='*',$arrCondition=array()){
		$arrUser = array();
		try{
			$arrUser = $this->find('all', array(
                    'fields' => $field,
        			'conditions' => $arrCondition,
                    'recursive'  => -1
			));
		}catch(Exception $ex){
			$this->log($ex->getMessage(),LOG_ERROR);
		}
		return $arrUser;
	}
    
	/**
	 * This funtion get userInfo
	 *
	 * @param  $userId
	 */
	function getUserInfo($userId) {
		try{
			$info = $this->find('first', array(
                                    'conditions' => array(
                                                        'id'            =>  $userId,
                                                        'delete_flag'   =>  0
                                                    ),
                                    'recursive'  => -1
			));
			if(isset($info['User'])) 
                return $info['User'];
            else
                return array();
		}
		catch(Exception $ex){
			$this->log($ex->getMessage(),LOG_ERROR);
		}
		return array();
	}
    /**
	 * Function update mutil
	 *
	 * @author vunn
	 *
	 * @param $arrayData
     * @date 12/09/2012
     * 
	 * @return true or false
	 */
	function updateMutil($arrData=array()){
		if(empty($arrData))
            return false;
		$arrUpdate = array();
        
		foreach($arrData AS $item){
			$arrUpdate[] = array(
                    'User' =>  $item
			);
		}
		return $this->saveMany($arrUpdate);
	}
	function delete($id){
		$sql ='DELETE FROM Users WHERE id = '.$id;
		try {
			$this->query($sql);
		} catch (Exception $ex) {
			$this->log($ex->getMessage(),LOG_ERROR);
		}
	}
	
	function updatebyConditon($arrData,$uid){
		$sql = "UPDATE ".$this->useTable." SET full_name= '".$arrData."' where id = ".$uid;
		debug($sql);
		try {
			$this->query($sql);
		} catch (Exception $ex) {
			$this->log($ex->getMessage(),LOG_ERROR);
		}
		return true;
	}
	
}
